<?php

  //
  // Memorii Web
  // script/create.php
  //
  // Creation of a new user account.
  //
  
  require_once('../const.php');
  include('../db/db.php');
  require('../ext/phpmailer/class.phpmailer.php');

  $success   = false;
  $error_msg   = '';

  // We get what we need
  if( isset($_POST['email']) && isset($_POST['password']) && isset($_POST['password_conf']) ) {
    
    $email     		  = $_POST['email'];
    $password   	  = $_POST['password'];
    $password_conf  = $_POST['password_conf'];
    
    // Fields aren't empty.
    if( $email!='' && $password!='' && $password_conf!='' ) {
      
      // Check if the address is valid
      if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
	      
	      // Check if the address is available (todo)
	      // ...
	      
	      // Password is correct
	      if( strcmp($password,$password_conf)==0 ) {
	        
	        // Generates root_folder_id (also used to activate the account)
	        $root_folder_id = db_generate_id();
	        
	        // Register the user (todo)
	        $mail = new PHPMailer();
	
					$mail->IsMail();
					$mail->From = 'studioamanga@gmail.com';
					$mail->FromName = 'Memorii';
					$mail->AddAddress($email);
					$mail->IsHTML(true);
					
					$mail->Subject = 'Memorii activation';
					$mail->Body    = '<html><body><p>Hello.</p><p>Thank you for your interest, unfortunately this service isn\'t available yet.</p><p>Follow this link to activate your account: <a href="'.$_MII_ROOT_URL.'/index.php?activate='.$root_folder_id.'">'.$_MII_ROOT_URL.'/index.php?activate='.$root_folder_id.'</a></p><p style="font-style:italic;">Studio AMANgA</p></body></html>';
					$mail->AltBody = 'Hello.\n\nThank you for your interest, unfortunately this service isn\'t available yet.\n\nFollow this link to activate your account: '.$_MII_ROOT_URL.'/index.php?activate='.$root_folder_id.'\n\nStudio AMANgA';
					
					if(!$mail->Send()) {
					   $error_msg = 'Unable to send confirmation mail. Please try again later.';
					}
	        else {
	        	$db_connection = db_connect();
	        	db_add_user($db_connection, $email, md5($password), $root_folder_id);
	        	db_disconnect($db_connection);
	        	
	          $success = true;
	        }
	      }
      	else {
     	   $error_msg = 'The password is incorrect.';
     	 	}
      }
	    else {
				$error_msg = 'This is not a valid email address.';
	    }
    }
    else {
      $error_msg = 'Please fill in all the forms.';
    }
  }
  else {
    $error_msg = 'System failure.';
  }
  
  // Everything is fine
  if( $success ) {
    echo '<div class="msg">We have just sent you your activation code, please check your mailbox.</div>';
    
    include('../../content/login_form.php');
  }
  // Something went wrong
  else {
    echo '<div class="msg">'.$error_msg.'</div>';
    
    include('../../content/create_form.php');
  }
?>